package net.dgg.dggcloud.service.jrcrm.service.customer;

import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.WhiteListDao;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.DepartmentCustomer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.WhiteList;
import net.dgg.dggcloud.service.jrcrm.service.cms.RuleConfigService;
import net.dgg.dggcloud.service.service.organization.OrganizationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: WhiteListService
 * @Author: 周潮
 * @Date: 2017年11月29 17:54:19
 * @Version V1.0
 */

@Service
public class WhiteListService extends BaseService{

    @Resource
    private WhiteListDao whiteListDao;
    @Resource
    private CustomerService customerService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private RuleConfigService ruleConfigService;

    /**
     * 根据条件查询白名单客户列表
     * @return
     */
    public List<Map> queryWhiteList(Map map){
        map.put("tableName", calcTableName(null == map.get("month") ? null : map.get("month").toString()));
        return whiteListDao.queryWhiteList(map);
    }

    /**
     * 根据条件查询白名单客户列表-count
     * @return
     */
    public Integer queryWhiteListCount(Map map){
        map.put("tableName", calcTableName(null == map.get("month") ? null : map.get("month").toString()));
        return whiteListDao.queryWhiteListCount(map);
    }

    /**
     * 查询白名单
     * @param map
     * month: 格式yyyy-MM-dd
     * deptCusId: 事业部库客户id
     * @return
     */
    public List<WhiteList> queryWhiteListByParam(Map map){
        map.put("tableName", calcTableName(null == map.get("month") ? null : map.get("month").toString()));
        if(null == map.get("deptCusId")){
            throw new BizException("查询白名单失败！事业部客户表id为空", 10006);
        }else{
            map.put("deptCusId", Long.parseLong(map.get("deptCusId").toString()));
        }
        return whiteListDao.queryWhiteListByParam(map);
    }

    /**
     * 踢回事业部
     * @param ids 白名单ids
     */
    public void updateWhiteListKickBackToDept(Long[] ids, User operator){
        for (Long id: ids) {
            if(null == id){
                throw new BizException("踢回事业部失败！找不到该白名单客户", 10006);
            }
            if(null == operator){
                throw new BizException("踢回事业部失败！获取操作人信息失败，请重试！", 10006);
            }
            WhiteList whiteList = repository.get(WhiteList.class, id);
            if(null == whiteList){
                throw new BizException("踢回事业部失败！找不到该白名单客户", 10006);
            }
            DepartmentCustomer departmentCustomer = repository.get(DepartmentCustomer.class, whiteList.getDepCustomerId());
            if(null == departmentCustomer){
                throw new BizException("踢回事业部失败！该客户不在事业部库客户中", 10006);
            }
            Customer customer = repository.get(Customer.class, whiteList.getCustomerId());
            if(null == customer){
                throw new BizException("踢回事业部失败！该客户不存在", 10006);
            }
            departmentCustomer.setPushStatus(0);//重置为未推送
            departmentCustomer.setUpdaterUser(operator);
            repository.saveOrUpdate(departmentCustomer);
            whiteList.setUpdaterUser(operator);
            whiteList.setStatus(5);//踢回事业部
            repository.saveOrUpdate(whiteList);
            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), WhiteList.TABLE_NAME, whiteList.getId(), CustomerConstant.CUS_OPERATE_WHITE_KICK, operator.getId(),"白名单踢回事业部");
        }
    }

    /**
     * 根据传入月份计算查询白名单表名
     * @param paramMonth
     * @return
     */
    private String calcTableName(String paramMonth){
        //如果当日与传入日期差大于90,则查询对应传入日期的月表
        if(StringUtils.isNotEmpty(paramMonth) && DateUtil.timeBetween(DateUtil.stringToDate(paramMonth, "yyyy-MM-dd"), new Date(),"day") > 90){
            return WhiteList.TABLE_NAME + "_" + paramMonth.substring(0, paramMonth.lastIndexOf("-")).replaceAll("-", "");
        }else {
            return  WhiteList.TABLE_NAME;
        }
    }

    /**
     * 白名单拨打电话回写是否拨打，以及更新对应事业部客户的隐藏天数
     * @param  whiteId：白名单客户id
     * @param  user：操作人
     */
    public void updateWhiteListIsCall(Long whiteId, User user){
        WhiteList whiteList = repository.get(WhiteList.class, whiteId);
        if(null != whiteList){
            whiteList.setIsCall(1);//已拨打
            whiteList.setUpdaterUser(user);
            if(null == whiteList.getFirstCallTime()){//白名单拨打电话只回写首次拨打的时间
                whiteList.setFirstCallTime(new Date());
            }
            repository.saveOrUpdate(whiteList);
            Customer customer = repository.get(Customer.class, whiteList.getCustomerId());
            if(null != customer){
                customer.setLastFollowContent("打电话");
                customer.setLastFollowInfo(user);
                customer.setUpdaterUser(user);
                repository.saveOrUpdate(customer);
            }
            DepartmentCustomer departmentCustomer = repository.get(DepartmentCustomer.class, whiteList.getDepCustomerId());
            if(null != departmentCustomer){
                Date lockTime;
                lockTime = null != departmentCustomer.getLockTime() ? departmentCustomer.getLockTime() : new Date();
                //查询登录人所在事业部
                Long deptId = organizationService.getOrganizationDepartmentId(user.getOrgId());
                //推送资源开发周期
                String days = ruleConfigService.getRuleConfigByMap(deptId, CustomerConstant.GZFL_KHTS_4);
                Integer hideDays = StringUtils.isNotEmpty(days) ? Integer.parseInt(days) : 0;
                departmentCustomer.setLockTime(DateUtil.dateAddDay(lockTime, hideDays));
                departmentCustomer.setUpdaterUser(user);
                repository.saveOrUpdate(departmentCustomer);
            }
        }
    }


    /**
     *白名单完成情况
     * @param map
     * @return
     */
    public Map queryCompleteSituation(Map map){
        return whiteListDao.queryCompleteSituation(map);
    }

    /**
     *根据事业部查询当前推送轮次的到期时间
     * @param map deptId：事业部id
     * @return
     */
    public String queryExpireDateByDeptId(Map map){
        Map result = whiteListDao.queryExpireDateByDeptId(map);
        if(null != result && null != result.get("expireDate")){
            return DateUtil.dateToString((Date) result.get("expireDate"), "MM.dd");
        }else {
            return "";
        }
    }

    public WhiteList getById(Long id){
        return this.repository.get(WhiteList.class,id);
    }

    /**
     * 踢除
     * @param ids 白名单ids
     */
    public void updateWhiteListKickCustomer(Long[] ids, User operator,String content){
        for (Long id: ids) {
            if(null == id){
                throw new BizException("剔除失败！找不到该白名单客户", 10006);
            }
            if(null == operator){
                throw new BizException("剔除失败！获取操作人信息失败，请重试！", 10006);
            }
            WhiteList whiteList = repository.get(WhiteList.class, id);
            if(null == whiteList){
                throw new BizException("剔除失败！找不到该白名单客户", 10006);
            }
            Customer customer = repository.get(Customer.class, whiteList.getCustomerId());
            if(null == customer){
                throw new BizException("剔除失败！该客户不存在", 10006);
            }
            whiteList.setUpdaterUser(operator);
            whiteList.setStatus(6);//踢除
            whiteList.setExt1(content);
            repository.saveOrUpdate(whiteList);
            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), WhiteList.TABLE_NAME, whiteList.getId(), CustomerConstant.CUS_OPERATE_WHITE_DETLETE, operator.getId(),"剔除白名单");
        }
    }
}
